package main

import (
	"io"

	"dzomc/tcp"
)

type LoraProtocol struct {
	data []byte
}

func (ep *LoraProtocol) Bytes() []byte {
	return ep.data
}

//处理协议数据格式
// func (ep *EchoProtocol) ReadPacket(reader io.Reader) (tcp.Packet, error) {
// 	rd := bufio.NewReader(reader)
// 	bytesData, err := rd.ReadBytes('\n')
// 	if err != nil {
// 		return nil, err
// 	}
// 	return &EchoProtocol{data: bytesData}, nil
// }
// func (ep *EchoProtocol) WritePacket(writer io.Writer, msg tcp.Packet) error {
// 	_, err := writer.Write(msg.Bytes())
// 	return err
// }

func (ep *LoraProtocol) ReadPacket(reader io.Reader) (tcp.Packet, error) {

	var head = make([]byte, 4) //数组切片
	_, err := io.ReadFull(reader, head)
	if err != nil {
		return nil, err
	}

	var buf = make([]byte, head[3]-4)
	_, err = io.ReadFull(reader, buf)
	if err != nil {
		return nil, err
	}

	head = append(head, buf...)
	// log.Println("head:", head)
	return &LoraProtocol{data: head}, nil

}

func (ep *LoraProtocol) WritePacket(writer io.Writer, msg tcp.Packet) error {
	_, err := writer.Write(msg.Bytes())
	return err
}
